// pages/cart/cart.js
import { getSetting, chooseAddress, openSetting, showModal, showToast, requestPayment } from '../../utils/asyncWx'
import regeneratorRuntime from '../../lib/runtime/runtime';
import { request } from '../../request/index'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        address: {},
        cart: [],
        totalPrice: 0,
        totalNum: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },
    onShow() {
        // 获取缓存中的收货地址
        const address = wx.getStorageSync('address')
        // 获取缓存中的商品数据
        let cart = wx.getStorageSync('cart') || []
        // 过滤后的数据
        cart = cart.filter(v => v.checked)
        // 总价格 总数量
        let totalPrice = 0
        let totalNum = 0
        cart.forEach(v => {

            totalPrice += v.num * v.goods_price
            totalNum += v.num

        })
        this.setData({
            cart, totalNum, totalPrice, address
        })
    },
    // 点击支付
    async handleOrderPay() {
        try {
            const token = wx.getStorageSync('token')
            // 判断是否存在token
            if (!token) {
                wx.navigateTo({
                    url: '/pages/auth/auth',

                })
                return;
            }
            // 创建订单
            // // 请求头参数
            // const header = { Authorization: token }
            // 订单总价格
            const order_price = this.data.totalPrice
            // 购买的数量
            // 收货地址
            const consignee_addr = this.data.address.all
            const cart = this.data.cart
            const goods = []
            cart.forEach(v => goods.push({
                goods_id: v.goods_id,
                goods_price: v.goods_price,
                goods_number: v.num
            }))
            const orderParams = { order_price, consignee_addr, goods }
            // 发送请求，创建订单
            const { order_number } = await request({ url: '/my/orders/create', data: orderParams, method: 'POST' })
            // 发送预支付请求
            const { pay } = await request({ url: '/my/orders/req_unifiedorder', method: 'POST', data: { order_number } })
            // 发起微信支付
            await requestPayment(pay)
            // 查询订单支付状态
            const res = await request({ url: '/my/orders/chkOrder', method: 'POST', data: { order_number } })
            await showToast({ title: '支付成功' })
            // 支付成功后删除已经选中的商品
            let newCart = wx.getStorageSync('cart')
            newCart = newCart.filter(v => !v.checked)
            wx.setStorageSync('cart', newCart)
            // 跳转到订单页面
            wx.navigateTo({
                url: '/pages/order/order',
            })

        } catch (error) {
            console.log(error);
        }

    }









})